// vue导出  FileSaver插件 
// 文件下载
axios.get(url_href,{responseType:"blob"}).then(res=>{
	const blob = new Blob([res.data]);
	let url = window.URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = url_href
	a.click();
	window.URL.revokeObjectURL(url)
})

// element-plus 文件上传和预览
{
	<el-upload
		:file-list="notifications.imgList" //绑定的文件列表
		action="/gateway/admin/sys-file/batch_upload" //上传地址
		:headers="notifications.header" //请求头
		:limit="10" //上传数量
		:on-preview="notifications.handlePictureCardPreview" //点击文件列表中已上传的文件时的钩子
		:on-success="notifications.successful" //文件上传成功狗子
		:on-remove="notifications.remove"//删除文件钩子
	>
		<el-icon><Plus /></el-icon>
	</el-upload>
	<el-dialog v-model="notifications.dialogVisible">
		<img w-full :src="notifications.dialogImageUrl" alt="Preview Image" />
	</el-dialog>

	handlePictureCardPreview(uploadFile){
		notifications.dialogImageUrl = uploadFile.url
		notifications.dialogVisible = true
	},
	successful(response,UploadFile,UploadFiles){
		notifications.imgList.push({name:response.data[0].originalFilename,url:response.data[0].fullUrl})
		console.log(notifications.imgList);
	},
	remove(file){
		const filePath = file.response.data[0].fullUrl;
		const i = notifications.imgList.findIndex(x => x.url == filePath);
		notifications.imgList.splice(i,1);
		console.log(notifications.imgList);
	},
}
// 防抖
{
	function debounce(fn,wait){
		var timer = null;
		return function(){
			if(timer !== null){
				clearTimeout(timer);
			}
			timer = setTimeout(fn,wait);
		}	
	}
		
	function handle(){
		console.log(Math.random());
	}
		
	window.addEventListener("resize",debounce(handle,1000));
}

//时间戳转换 YY-MM-DD
{
	const getTiem = (timestamp) => {
		var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
		var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
		var h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
		var m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
		var s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
		return Y+M+D+h+m+s;
	}	
}
// 获取文件md5
{
	let fileMd5 = await new Promise((resolve, reject) => {
		let fileReader = new FileReader();
		let dataFile = item.raw;
		let spark = new SparkMD5;
		fileReader.readAsBinaryString(dataFile)
		//异步执行函数
		fileReader.onload = function(e){
			console.log(e);
			spark.appendBinary(e.target.result);
			let md5 = spark.end()
			console.log(md5);
			resolve(md5)
		}
    })
}
// js字节转换单位
{
	filterSize(size){
        if (!size) return '';
        if (size < pow1024(1)) return size + ' B';
        if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + ' KB';
        if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + ' M';
        if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + ' G';
        return (size / pow1024(4)).toFixed(2) + ' T'
        // 求次幂
        function pow1024(num) {
            return Math.pow(1024, num)
        }
    }
}
// 时间加八小时
{
	//dateTimeString 时间 hoursToAdd 加小时数
    addHoursToDateTimeAndFormat(dateTimeString, hoursToAdd) {
        const dateObj = new Date(dateTimeString);
        dateObj.setHours(dateObj.getHours() + hoursToAdd);
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');
        const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return formattedDateTime;
    },
}
// 列表组装成树结构
{
	buildTreeFromArray(array) {
		const treeMap = {};
		const tree = [];
		// 创建一个以id为键的对象映射
		array.forEach(item => {
			treeMap[item.id] = { ...item, children: [] };
		});
		console.log(treeMap);
		// 构建树
		array.forEach(item => {
			const parent = treeMap[item.parent_id];
			// console.log(parent);
			if (parent) {
				parent.children.push(treeMap[item.id]);
			} else {
				tree.push(treeMap[item.id]);
			}
		});

		return tree;
	}
}
// 解析xlsx
{
	import * as xlsx from "xlsx";
	async downLoad() {
        const file = region.fileList[0].raw
        console.log(file);
        const fileReader = new FileReader()
        fileReader.onload = async (ev) => {
            const workbook = xlsx.read(ev.target.result, {
            type: "binary"
            })
            console.log(workbook);
            const wsname = workbook.SheetNames[0]
            console.log(wsname);
            const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname])
            console.log('ws:',ws) // 转换成json的数据
            const transformedArray = ws.map(item => ({
                calDate: item['公历日期(YYYY-MM-DD)'],
                event: item['事件']
            }));
            console.log(transformedArray);
            try{
                const res = await service.post(`/config/calendar/import`,transformedArray)
                // uploadRef.value.submit()
                region.dialogVisible = false
                await region.getList(region.monthValue)
            }catch(err){
                ElMessage.error('不允许访问');
            }
        }
        fileReader.readAsBinaryString(file)
        
    },
}
// 导出 Excel
{
	import * as XLSX from 'xlsx';

	// 数据
	const data = [
	  { Name: "John Doe", Age: 30, City: "New York" },
	  { Name: "Jane Doe", Age: 25, City: "San Francisco" },
	  { Name: "Bob Smith", Age: 35, City: "Los Angeles" }
	];

	// 自定义表头
	const header = ["名字", "年龄", "城市"];

	// 将数据转换为符合 xlsx 格式的格式
	const formattedData = data.map(item => ({
	  "名字": item.Name,
	  "年龄": item.Age,
	  "城市": item.City
	}));

	// 创建一个工作簿（Workbook）
	const workbook = XLSX.utils.book_new();

	// 创建一个工作表（Worksheet）
	const worksheet = XLSX.utils.json_to_sheet(formattedData, { header });

	// 将工作表添加到工作簿
	XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

	// 将工作簿保存为 Excel 文件
	XLSX.writeFile(workbook, 'output.xlsx');

	console.log('Excel 文件已生成');

}

// webScoket
{
	const scoket = reactive({
		ws:null,
		sendTimer:null,
		init(){
			scoket.ws = new WebSocket(`wss://kproxy.prod.hywea.cn:50443/infra/ws?token=${stroe.getters.token}`)
			console.log('websocket',scoket.ws);
			scoket.ws.onopen = () => {
				console.log("连接成功");
				scoket.scoketSend()
			},
			scoket.ws.onmessage = async (event) => {
				console.log("接收");
				message.data = JSON.parse(event.data)
				console.log(message.data);
				if(message.data.notifyType == 2){
					message.title = '系统公告'
					message.template = announcement(message.data.content,message.data.createTime)
				}
				message.openMessage()
			}
			//  //连接发生错误的回调方法
			scoket.ws.onerror = () => {
				console.log("连接发生错误");
				clearInterval(scoket.sendTimer)
			};
			//连接关闭的回调方法
			scoket.ws.onclose = () => {
				console.log("连接关闭");
				clearInterval(scoket.sendTimer)
			}
		},
		scoketSend(){
			scoket.sendTimer = setInterval(() => {
				console.log('发送成功');
				scoket.ws.send({})
			}, 20000);
		}
	})
}
// 下载文件 zip
{
	
	import JSZip from "jszip";
	import FileSaver from "file-saver";
	var zip = new JSZip();
	for(let i = 0; i <  table.multipleSelectionList.length; i++){
		if( table.multipleSelectionList[i].fileType == 'folder'){
			// ElMessage.error('文件夹不允许下载')
		}else{
			file_ids.push(table.multipleSelectionList[i].id)
			let url = '/reslib-standalone/s3/' + table.multipleSelectionList[i].s3_path
			let { data } = await axios({
				method: "get",
				url: url,
				responseType: "blob",
			});
			console.log(data);
			zip.file(url.split("/")[url.split("/").length - 1], data);
		}
	}
	zip.generateAsync({ type: "blob" }).then(async function (content) {
		FileSaver.saveAs(content, props.directory?.name + ".zip");
	});
}